// oss 图片墙上传
import React from 'react';
import { observer, useLocalStore } from 'mobx-react-lite';
import { Upload, Modal } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { UploadProps, UploadFile } from 'antd/lib/upload/interface';
import { config } from '~/config/config';

interface Props extends Omit<UploadProps, 'value' | 'onChange'>{
  value?: UploadProps['fileList']
  onChange?: UploadProps['onChange']
  max?: number // 默认限制最大上传个数：20，0 为不限制
  size?: number // 默认限制最大上传尺寸：10 MB
}

// 回显处理 (图片上传，文件上传)
export const formatFileList = (list: Array<any> | undefined): Array<UploadFile> => {
  let uid = 0;
  const genUid = () => {
    uid += 1;
    return uid;
  };

  if (!list) {
    return [];
  }

  const formatedList = [] as Array<UploadFile>;

  list.forEach((v) => {
    const obj = {
      uid: genUid().toString(),
      name: v.replace(/^.*[\\/]/, ''),
      status: 'done' as const,
      url: `${config.ossUrl}${v as string}`,
      size: 0,
      type: '',
      response: {
        data: v,
      },
    };

    formatedList.push(obj);
  });

  return formatedList;
};

const getBase64 = (file: any) => new Promise((resolve, reject) => {
  const reader = new FileReader();
  reader.readAsDataURL(file);
  reader.onload = () => resolve(reader.result);
  reader.onerror = (error) => reject(error);
});

export const PictureUploader = observer((props: Props) => {
  const state = useLocalStore(() => ({
    previewVisible: false,
    previewImage: '',
    // fileList: [] as Array<UploadFile>,
  }));

  const {
    value,
    onChange,
    max = 20,
    size = 10000,
    ...rest
  } = props;

  const handleCancel = () => {
    state.previewVisible = false;
  };

  const handlePreview = async (file: any) => {
    if (!file.url && !file.preview) {
      // 上传失败时预览
      file.preview = await getBase64(file.originFileObj);
    }

    state.previewImage = file.url || file.preview;
    state.previewVisible = true;
  };

  const handleChange = ({ fileList }: any) => {
    if (value && value.length > 0) {
      value.forEach((v) => {
        if (v.status === 'done') {
          v.url = `${config.ossUrl}${v.response.data as string}`;
        }
      });
    }

    if (onChange) {
      onChange(fileList);
    }
  };

  const uploadButton = (
    <div>
      <PlusOutlined
        style={{
          fontSize: '24px',
          color: '#9DAFCC',
        }}
      />
    </div>
  );

  // 上传按钮展示
  const setUploadButton = (_value: Array<UploadFile> | undefined, _max: number) => {
    if (_max === 0) {
      // 不限制上传个数
      return uploadButton;
    }

    if (!_value) {
      return uploadButton;
    }

    if (_value.length < _max) {
      return uploadButton;
    }

    return null;
  };

  const { previewVisible, previewImage } = state;
  const uploadConfig = {
    action: `${config.remoteUrl}/file/oss_upload`,
    listType: 'picture-card' as const,
    ...'value' in props ? {
      fileList: value,
    } : {},
    onPreview: handlePreview,
    onChange: handleChange,
    withCredentials: true,
  };
  const previewModalConfig = {
    visible: previewVisible,
    onCancel: handleCancel,
    footer: null,
  };

  return (
    <div className="clearfix">
      <Upload
        {...uploadConfig}
        {...rest}
      >
        {setUploadButton(value, max)}
      </Upload>
      <Modal
        {...previewModalConfig}
      >
        <img alt="example" style={{ width: '100%' }} src={previewImage} />
      </Modal>
    </div>
  );
});
